package com.mchsdk.open;

import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;


import com.mchsdk.paysdk.activity.TransparencyActivity;
import com.mchsdk.paysdk.bean.ChangePlayerLevel;
import com.mchsdk.paysdk.bean.ChangeRoleName;
import com.mchsdk.paysdk.activity.LoginActivity;
import com.mchsdk.paysdk.bean.DeviceInfoModel;
import com.mchsdk.paysdk.bean.FlagControl;
import com.mchsdk.paysdk.bean.InitModel;
import com.mchsdk.paysdk.bean.MCPayModel;
import com.mchsdk.paysdk.bean.OffLineAnnounceModel;
import com.mchsdk.paysdk.bean.PersonalCenterModel;
import com.mchsdk.paysdk.bean.SdkDomain;
import com.mchsdk.paysdk.bean.AntiAddictionModel;
import com.mchsdk.paysdk.bean.UploadRole;
import com.mchsdk.paysdk.dialog.DialogUtil;
import com.mchsdk.paysdk.miui.XiaomiUtil;
import com.mchsdk.paysdk.miui.XmDgModel;
import com.mchsdk.paysdk.server.MCHFloatService;
import com.mchsdk.paysdk.utils.Lolly;
import com.mchsdk.paysdk.utils.MCLog;

public class MCApiFactory {

    private static final String TAG = "MCApiFactory";

    private Context mContext;

    /**
     * 退出回调接口
     */
    private IGPExitObsv exitObsv;

    /**
     * 修改玩家等级回调接口
     */
    private ChangePlayerLevelCallback mLevelCallback;
    /**
     * 个人中心退出回调接口，判断用不能合并
     */
    private IGPExitObsv exitObsvPerson;
    protected IGPUserObsv mUserObsv;


    public IGPUserObsv getmUserObsv() {
        if (mUserObsv == null) {
            return null;
        }
        return mUserObsv;
    }

    /**
     * 防沉迷到时间通知
     */
    private AnnounceTimeCallBack announceTimeCallBack;

    private boolean floatingIsShow = false;

    private static MCApiFactory instance;

    private Class<?> loginClass = null;

    /**
     * 首次调用悬浮窗
     */
    private boolean isFirst = true;

    /**
     * 测试参数
     */
    private Map<String, String> map = null;

    public static MCApiFactory getMCApi() {
        if (null == instance) {
            instance = new MCApiFactory();
        }
        return instance;
    }

    private MCApiFactory() {
        map = new HashMap<String, String>();
    }

    public Context getContext() {
        return mContext;
    }

    public String getMCHSdkVersion() {
        return "4.0.1";
    }

    /**
     * 初始化方法
     *
     * @param con 上下文
     */
    public void init(Context con) {
        init(con, false);
    }

    public void init(Context con, boolean isDebug) {
        init(con, null, isDebug);
    }

    public void init(Context con, IGPSDKInitObsv initObsv) {
        init(con, initObsv, false);
    }

    public void init(Context con, IGPSDKInitObsv initObsv, boolean isDebug) {
        if (null == con) {
            MCLog.e(TAG, "初始化上下文为空");
            return;
        }
        MCLog.isDebug = isDebug;
        InitModel.init().doInit(con, initObsv);
    }

    /***
     * 参数为 个人中心里面点击退出登录跳转的目标activity; 设置个人中心里面退出回调接口
     */
    public void initExitFromPersonInfoParams(IGPExitObsv exitObsv) {
        if (null != exitObsv) {
            this.exitObsvPerson = exitObsv;
        }
    }

    public void initAnnounceTimeCallBack(AnnounceTimeCallBack callBack) {
//        if (null != announceTimeCallBack) {
        this.announceTimeCallBack = callBack;
//        }
    }

    /**
     * 防沉迷时间提醒
     *
     * @return
     */
    public AnnounceTimeCallBack getAnnounceTimeCallBack() {
        if (announceTimeCallBack == null) {
            return null;
        }
        return announceTimeCallBack;

    }


    /**
     * sdk 登录
     *
     * @param context  上下文
     * @param userObsv 登录回调
     */
    public void startlogin(Context context, IGPUserObsv userObsv) {
        if (null == context) {
            MCLog.e(TAG, "fun#startlogin context is null");
            return;
        }
        if (null != userObsv) {
            mUserObsv = userObsv;
        }
        mContext = context;
        Intent loginIntent = new Intent(context, TransparencyActivity.class);
        mContext.startActivity(loginIntent);
    }

    /**
     * 修改玩家等级
     */
    public void changePlayerLevel(String role_level, ChangePlayerLevelCallback levelCallback) {

        if (null == role_level) {
            MCLog.e(TAG, "fun#changePlayerLevel role_level is null");
            return;
        }
        ChangePlayerLevel playerLevelActivity = new ChangePlayerLevel("2", role_level, levelCallback);
        playerLevelActivity.change();
    }

    /**
     * 修改角色名称
     */

    public void changeRoleName(String role_name, ChangeRoleNameCallback roleNamecallback) {
        if (null == role_name) {
            MCLog.e(TAG, "fun#changePlayerLevel role_name is null");
            return;
        }
        ChangeRoleName roleNameActivity = new ChangeRoleName("1", role_name, roleNamecallback);
        roleNameActivity.change();
    }

    /**
     * 验证登录
     */
    public boolean isLogin() {
        String account = PersonalCenterModel.getInstance().getAccount();
        return !TextUtils.isEmpty(account);
    }

    public void loginout(Context context) {
        PersonalCenterModel.getInstance().clearUserLoginInfo(context);
    }


    /**
     * 退出
     */
    public void exitDialog(Context context, IGPExitObsv exitObsv) {
        if (null == context) {
            MCLog.e(TAG, "fun#startlogin context is null");
            return;
        }
        if (null != exitObsv) {
            this.exitObsv = exitObsv;
        } else {
            this.exitObsv = null;
            MCLog.w(TAG, "fun#startlogin IGPExitObsv is null");
        }
        DialogUtil.mch_alert_exit(context, context);
    }

    /**
     * 开始支付
     *
     * @param context   上下文
     * @param orderInfo 商品信息
     * @param pck       支付回调
     */
    public void pay(Context context, OrderInfo orderInfo, PayCallback pck) {
        MCPayModel.Instance().pay(context, orderInfo, pck);
    }

    XmDgModel model;

    @SuppressLint("NewApi")
    public void startFloating(final Context context) {
        if (!floatingIsShow) {
            floatingIsShow = true;
            MCLog.e(TAG, "fun#startFloating");
            if (model == null) {
                model = new XmDgModel(context);
            }
            //小米手机之外的悬浮圈窗权限检查操作
            if (!XiaomiUtil.isMIUI()) {
                model.permission(context);
            }
            //小米手机的悬浮圈窗权限检查操作
            if (XiaomiUtil.isMIUI() && isFirst) {
                isFirst = false;
                final int version = Build.VERSION.SDK_INT;
                if (version >= 19 && !XiaomiUtil.isMiuiFloatWindowOpAllowed(context)) {
                    model.showxiaomidg();
                } else {
                    Intent serviceStart = new Intent(context, MCHFloatService.class);
                    context.startService(serviceStart);
                }
            } else if (XiaomiUtil.isMIUI() && !isFirst) {
                if (Build.VERSION.SDK_INT >= 19) {
                    if (XiaomiUtil.isMiuiFloatWindowOpAllowed(context)) {
                        Intent serviceStart = new Intent(context, MCHFloatService.class);
                        context.startService(serviceStart);
                    }
                } else {
                    Intent serviceStart = new Intent(context, MCHFloatService.class);
                    context.startService(serviceStart);
                }
            }
        }
    }

    public void stopFloating(Context context) {
        if (floatingIsShow) {
            floatingIsShow = false;
            MCLog.e(TAG, "fun#stopFloating");
            Intent serviceStart = new Intent(context, MCHFloatService.class);
            context.stopService(serviceStart);
        }
    }

    public IGPUserObsv getLoginCallback() {
        return mUserObsv;
    }

    protected IGPExitObsv getExitObsv() {
        return exitObsv;
    }

    public Class<?> getLoginClass() {
        if (null == loginClass) {
            return null;
        }
        return loginClass;
    }

    public IGPExitObsv getExitFromPersonInfo() {
        if (null == exitObsvPerson) {
            return null;
        }
        return exitObsvPerson;
    }

    /**
     * 渠道id和渠道名称，一般联运不会特殊要求，这里填写固定值“0”和“自然注册”即可
     *
     * @param promoteId      渠道id
     * @param promoteAccount // 渠道名称
     * @param gameId         游戏id(编号)
     * @param gameName       游戏名称
     * @param gameAppid      游戏appid
     * @param paysdk_signkey 访问秘钥： (SDK访问服务器时的加密key)
     * @param paysdk_address 联运SDK服务器地址
     */
    public void setParams(String promoteId, String promoteAccount,
                          String gameId, String gameName, String gameAppid, String paysdk_signkey, String paysdk_address) {
        map.put(SdkDomain.KEY_CHANNEL_ID, promoteId);
        map.put(SdkDomain.KEY_CHANNEL_NAME, promoteAccount);
        map.put(SdkDomain.KEY_GAME_ID, gameId);
        map.put(SdkDomain.KEY_GAME_NAME, gameName);
        map.put(SdkDomain.KEY_GAME_APP_ID, gameAppid);
        map.put(SdkDomain.KEY_SIGNKEY, paysdk_signkey);
        map.put(SdkDomain.KEY_IP_ADDRESS, paysdk_address);
    }

    /**
     * unity时候用这个
     *
     * @param value
     */
    public void setParamsUnity(String value) {
        map.put("paysdk_signkey_unity", value);
    }

    public Map<String, String> getMap() {
        if (map == null) {
            return new HashMap<String, String>();
        }
        return map;
    }

    /**
     * 请求防沉迷
     */
    public void requestAntiAddiction() {

        if (FlagControl.isLogin && !FlagControl.isStart) {
            AntiAddictionModel.getInstance().requestAntiAddictionInfo();
        }
    }


    /**
     * 下线通知
     */
    public void offLineAnnounce(Context context) {
        if (FlagControl.isLogin /*&& FlagControl.isStart*/ && !FlagControl.isJump) {
            OffLineAnnounceModel offLineAnnounceModel = new OffLineAnnounceModel(context);
            offLineAnnounceModel.offLineAnnouce();
        }

    }

    /**
     * 获取运营商
     *
     * @param context
     */

    public String getNetOperator(Context context) {
        return DeviceInfoModel.getInstance().getNetOperator(context);
    }

    /**
     * 获取联网方式
     *
     * @param context
     */
    public String getNetMode(Context context) {
        return DeviceInfoModel.getInstance().getNetMode(context);
    }

    /**
     * 获取手机型号
     *
     * @return
     */
    public String getPhoneModel() {
        return DeviceInfoModel.getInstance().getPhoneModel();
    }

    /**
     * 获取操作系统
     * Android
     *
     * @return
     */
    public String getOS() {
        return DeviceInfoModel.getInstance().getOS();
    }


    /**
     * 获取屏幕分辨率
     *
     * @return
     */
    public String getResolution(Context context) {
        return DeviceInfoModel.getInstance().getResolution(context);
    }

    /**
     * 获取设备唯一码
     *
     * @param context
     * @return
     */
    public String getDeviceNo(Context context) {
        return DeviceInfoModel.getInstance().getDeviceNo(context);
    }

    /**
     * 游戏从后台开始，开始计时
     */
    public void onResume() {
        MCApiFactory.getMCApi().requestAntiAddiction();
        FlagControl.isJump2 = false;
    }

    /**
     * 游戏进入后台或退出游戏时，请求下线（下线通知）
     */
    public void onStop(Context context) {
        MCApiFactory.getMCApi().offLineAnnounce(context);
    }

    /**
     * 查看log
     */
    public void showLog(final Activity activity, String[] tags) {
        if (model == null) {
            model = new XmDgModel(activity);
        }
        if (XiaomiUtil.isMIUI()) {
            if (Build.VERSION.SDK_INT >= 19 && !XiaomiUtil.isMiuiFloatWindowOpAllowed(activity)) {
                model.showxiaomidg();
            } else {
                Lolly.getInstance().showLolly(activity, tags);
            }
        } else {
            if (Build.VERSION.SDK_INT > 24) {
                if (!Settings.canDrawOverlays(activity)) {
                    new AlertDialog.Builder(activity).setTitle("悬浮窗权限")
                            .setMessage("您需要开启悬浮窗权限才可以享受更多服务！").setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                            intent.setData(Uri.parse("package:" + activity.getPackageName()));
                            activity.startActivityForResult(intent, 100);
                        }
                    }).show();
                } else {
                    Lolly.getInstance().showLolly(activity, tags);
                }
            } else {
                Lolly.getInstance().showLolly(activity, tags);
            }
        }
    }

    /**
     * 隐藏log
     *
     * @param context
     */
    public void hideLog(Context context) {
        Lolly.getInstance().hideLolly(context);
    }

    public void stopService() {
        Lolly.getInstance().stop();
    }


    /**
     * @param context
     * @param gameId       游戏id
     * @param serverId     服务器id
     * @param serverName   服务器名称
     * @param roleName     角色名称
     * @param roleLevel    角色等级
     * @param roleCallBack 回调
     */
    public void uploadRole(Context context, String gameId, String serverId, String serverName,
                           String roleName, String roleLevel, UploadRoleCallBack roleCallBack) {
        if (null == roleLevel || null == serverName) {
            MCLog.e(TAG, "fun#uploadRole userId、roleLevel、serverName must be not null\n"
                    + "serverName\t" + serverName + "\n"
                    + "roleName\t" + roleName + "\n"
                    + "roleLevel\t" + roleLevel);
            return;
        }
        UploadRole uploadRole = new UploadRole(gameId, serverId, serverName,
                roleName, roleLevel, roleCallBack);
        uploadRole.upload();
    }
}
